#include "DispatchHandler.h"
#include "JME_JsonFile.h"
#include "JME_RPCManager.h"
#include "GameServer.h"
#include "RPC_dispatch.pb.h"

#include "json/json.h"

#include "account.pb.h"

void DispatchHandler::init()
{
#define REG_MSG_HANDLER(msgId, msgHandler) regMessageHandler(msgId, boost::bind(&DispatchHandler::msgHandler, _1, _2))


#undef REG_MSG_HANDLER
}

void DispatchHandler::requestJoinGame(int net, const google::protobuf::Message* params)
{
	auto proto = static_cast<const RPC_RequestHandle*>(params);
	
	server_join_game_response response;
	response.set_state(server_join_game_response_JoinState_AuthError);

	__TRY__
		do
		{
			client_request_join_game client_proto;
			client_proto.ParseFromString(proto->params());

			auto account_id = client_proto.account_id();
			auto server_id = client_proto.server_id();
			auto& auth_key = client_proto.auth_key();

			auto isAccountAuth = [](int account_id, int server_id, const string& key)
			{
				__TRY__
					MongodbConnHelper conn(GameServer::getInstance()->getMongoDBPool());

					static string dbname = boost::str(boost::format("server_%d.account_auth") % GameServer::getInstance()->_serverId);
					Json::Value v;
					conn->selectJson(dbname, BSON("account_id"<<account_id<<"auto_key"<<key<<"server_id"<<server_id), &v);

					return !v.isNull();
				__CATCH_CHAR_ERROR__

					LOGE("Try to get db connector error ==> [ %s ]", e);

				__TRY_END__

				return false;
			};
			if (!isAccountAuth(account_id, server_id, auth_key))
				break;
			response.set_state(server_join_game_response_JoinState_JoinGame);
		}while(0);
	__CATCH_STD_EXCEPT_ERROR__

		LOGE("Parse protobuf error ==> [ %s ]", e.what());

	__TRY_END__

	{
		RPC_SendClient p;
		p.set_msg_id(server_join_game_response_MsgId_responseJoinGame);
		p.set_net_id(net);
		p.set_params(response.SerializeAsString());

		GETRPC(proto->gate().c_str())->callRpcMethod("sendClient", &p);
	}
}

